package com.Controller;

import  com.Service.OrderService;
import com.pojo.OrderVO;
import com.pojo.User;

import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/front/order")
public class FrontOrderController {
    @Autowired
    private OrderService orderService;

    @GetMapping("/my")
    public String myOrders(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/front/user/login";
        }
        List<OrderVO> orderList = orderService.findOrdersByUserId(user.getId());
        model.addAttribute("orderList", orderList);
        return "front/order_list";
    }

    @PostMapping("/confirm")
    public String confirmOrder(@RequestParam("productIds") List<Long> productIds,
                               @RequestParam("quantities") List<Integer> quantities,
                               @RequestParam(value = "selected", required = false) List<Long> selectedIds,
                               HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/front/user/login";
        }

        // 没选商品
        if (selectedIds == null || selectedIds.isEmpty()) {
            redirectAttributes.addFlashAttribute("error", "请先选择要结算的商品");
            return "redirect:/front/cart";
        }

        // 构建选中的商品与数量映射
        Map<Long, Integer> selectedMap = new HashMap<>();
        for (int i = 0; i < productIds.size(); i++) {
            Long pid = productIds.get(i);
            if (selectedIds.contains(pid)) {
                selectedMap.put(pid, quantities.get(i));
            }
        }

        // 调用 service 创建订单
        orderService.createOrder(user.getId(), selectedMap);

        return "redirect:/front/order/my";
    }
}
